<?php
class Document extends Doctrine_Record {
		
	public function setTableDefinition() {
		/*
		$this->hasColumn('id', 'integer', 4, 
			array(
				'unsigned' => true,
      	'primary' => true,
				'notnull' => true,
				'default' => 0,
				'autoincrement' => true,
				'comment' => 'Llave primaria: Unico id de documento.'
      )
    );
    */
    $this->hasColumn('title', 'string', 255,
    	array(
				'notnull' => true,
    		'comment' => 'titulo del documento'
      )
    );
    
    $this->hasColumn('authors', 'string', 255,
    	array(
				'notnull' => true,
    		'comment' => 'Nombre de los autores en el formato Primer Apellido, Nombre.'
      )
    );
    
    $this->hasColumn('documentType', 'integer', 1,
    	array(
				'notnull' => true,
    		'comment' => 'tipo de documento. Este campo es una referencia master-detail de la tabla DocumentType'
      )
    );
    
    $this->hasColumn('year', 'string', 255,
    	array(
    		'comment' => 'Nombre de los autores en el formato Primer Apellido, Nombre.'
      )
    );
    
    $this->hasColumn('pages', 'string', 255,
    	array(
    		'comment' => 'paginas que contiene el documento en una string'
      )
    );
    
    $this->hasColumn('publishedin', 'string', 255,
    	array(
    		'comment' => 'donde fue publicado el documento'
      )
    );
    
    $this->hasColumn('abstract', 'string', 65535,
    	array(
    		'comment' => 'resumen del documento'
      )
    );
    
    $this->hasColumn('keywords', 'string', 255,
    	array(
    		'comment' => 'Author supplied keywords in the format keyword1; keyword2; ... keywordn;.'
      )
    );
    
    $this->hasColumn('tags', 'string', 255,
    	array(
    		'comment' => 'Tags related to the document. tag1; tag2; ... tagn;.'
      )
    );
    
    $this->hasColumn('createdBy', 'integer', 4,
    	array(
    		'notnull' => true,
    		'comment' => 'Author who has created the document.'
      )
    );
    
    $this->hasColumn('updatedBy', 'integer', 4,
    	array(
    		'notnull' => true,
    		'comment' => 'Author who has been the last documents modifier.'
      )
    );
	}
	
	public function setUp() {
		$this->hasOne('User as createdBy', 
			array(
      	'local' => 'createdBy',
        'foreign' => 'uid'
      )
    );
    
    $this->hasOne('User as updatedBy', 
			array(
      	'local' => 'updatedBy',
        'foreign' => 'uid'
      )
    );
		
		$this->hasMany('Url as urls', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasMany('File as files', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    /*
     * Specializations
     */
    $this->hasMany('Catalog as catalogs', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasOne('Thesis as thesis', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasOne('MasterThesis as masterThesis', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasOne('PhdThesis as phdThesis', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasOne('Book as book', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasOne('Encyclopedia as encyclopedia', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->hasOne('MagazineArticle as magazineArticle', 
			array(
      	'local' => 'id',
        'foreign' => 'document_id'
      )
    );
    
    $this->actAs('Timestampable');
	}
	
	/**
	 * Convert the document array to a flat document array
	 * @return flat array
	 */
	public function toFlatArray() {
		$objectModel = $this->lookupObjectModel();	
		
		$result = $this->toArray();
		
		foreach( $result[$objectModel] as $key => $value ) {
			if( $key != 'id' && $key != 'document_id') {
				$result[$key] = $value;
			}	
		}
		
		unset($result[$objectModel]);
		
		return $result;
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	public function findByDocumentTypeWithDetails() {
		$objectModel = $this->lookupObjectModel();
		
		$q = Doctrine_Query::create()
				->select('d.*, dt.*, f.*, u.*, c.*')
				->from('Document d')
				->leftJoin('d.'.$objectModel.' dt')
				->leftJoin('d.files f')
				->leftJoin('d.urls u')
				->leftJoin('d.catalogs c')
				->where('d.id = ? AND d.documentType = ?', array($this->id, $this->documentType) );
				
		$details = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
		if( count($details) == 0 ) {
			return null;	
		}
		
		foreach( $details[0][$objectModel] as $key => $value ) {
			if( $key != 'id' && $key != 'document_id') {
				$details[0][$key] = $value;
			}	
		}
		
		unset($details[0][$objectModel]);
		
		return $details[0];
	}
	
	/**
	 * 
	 * @return string
	 */
	private function lookupObjectModel() {
		if( $this->documentType == DOCUMENTTYPE_THESIS ) {
			return 'thesis';
		}	
		else if( $this->documentType == DOCUMENTTYPE_MASTER_THESIS ) {
			return 'masterThesis';
		}
		else if( $this->documentType == DOCUMENTTYPE_PHD_THESIS ) {
			return 'phdThesis';
		}
		else if( $this->documentType == DOCUMENTTYPE_MAGAZINE_ARTICLE ) {
			return 'magazineArticle';
		}
		else if( $this->documentType == DOCUMENTTYPE_BOOK ) {
			return 'book';
		}
		else if( $this->documentType == DOCUMENTTYPE_ENCYCLOPEDIA ) {
			return 'encyclopedia';
		}
		
		return null;
	}
	
	/**
	 * 
	 * @param unknown_type $document
	 * @return unknown_type
	 */
	public function documentTypeMapper() {
		switch( $this->documentType ) {
			case DOCUMENTTYPE_THESIS: 
				return $this->thesis;
				
			case DOCUMENTTYPE_MASTER_THESIS: 
				return $this->masterThesis;
				
			case DOCUMENTTYPE_PHD_THESIS: 
				return $this->phdThesis;
				
			case DOCUMENTTYPE_MAGAZINE_ARTICLE: 
				return $this->magazineArticle;
				
			case DOCUMENTTYPE_BOOK: 
				return $this->book;
				
			case DOCUMENTTYPE_ENCYCLOPEDIA: 
				return $this->encyclopedia;
				
			default:
				return null;
		}
	}
	
	/**
	 * Create an specific documentType
	 * @param int $documentType
	 * @return nothing
	 */
	public function documentTypeFactory($documentType) {
		switch( $documentType ) {
			case DOCUMENTTYPE_THESIS: 
				$this->documentType = DOCUMENTTYPE_THESIS;
				$this->thesis = new Thesis();
				break;
				
			case DOCUMENTTYPE_MASTER_THESIS: 
				$this->documentType = DOCUMENTTYPE_MASTER_THESIS;
				$this->masterThesis = new MasterThesis();
				break;
				
			case DOCUMENTTYPE_PHD_THESIS: 
				$this->documentType = DOCUMENTTYPE_PHD_THESIS;
				$this->phdThesis = new PhdThesis();
				break;
				
			case DOCUMENTTYPE_MAGAZINE_ARTICLE: 
				$this->documentType = DOCUMENTTYPE_MAGAZINE_ARTICLE;
				$this->magazineArticle = new MagazineArticle();
				break;
				
			case DOCUMENTTYPE_BOOK: 
				$this->documentType = DOCUMENTTYPE_BOOK;
				$this->book = new Book();
				break;
				
			case DOCUMENTTYPE_ENCYCLOPEDIA: 
				$this->documentType = DOCUMENTTYPE_ENCYCLOPEDIA;
				$this->encyclopedia = new Encyclopedia();
				break;
		}	
	}
	/**
	 * Change current documentType of a new one as $newDocumentType
	 * @param int $newDocumentType
	 * @return none
	 */
	public function changeDocumentType($newDocumentType) {
		$this->documentTypeMapper()->delete();
		// crear the related record
		// Read the topic Clearing Related Record of Chapter 8: Working with Models
		// from Doctrine manuel for PHP
		$this->clearRelated($this->lookupObjectModel());
		$this->documentTypeFactory($newDocumentType);
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	public function createDetailsByDocumentType() {
		$this->documentTypeFactory($this->documentType);	
	}
		
	/**
	 * Assign new values stored in $data 
	 * @param array $data
	 * @return unknown_type
	 */
	public function updateValues(array $data) {
		if( isset($data['title']) ) {
			$this->title = $data['title'];
		}
		if( isset($data['authors']) ) {
			$this->authors = $data['authors'];
		}
		if( isset($data['year']) ) {
			$this->year = $data['year'];
		}
		if( isset($data['pages']) ) {
			$this->pages = $data['pages'];
		}
		if( isset($data['publishedin']) ) {
			$this->publishedin = $data['publishedin'];
		}
		if( isset($data['abstract']) ) {
			$this->abstract = $data['abstract'];
		}
		if( isset($data['tags'])) {
		  $this->tags = $data['tags'];
		}
		if( isset($data['keywords']) ) {
			$this->keywords = $data['keywords'];
		}
		if( isset($data['createdBy']) ) {
			$this->createdBy = $data['createdBy'];
		}
		if( isset($data['updatedBy']) ) {
			$this->updatedBy = $data['updatedBy'];
		}
		if( isset($data['urls'])) {
  		$url = new Url();
  		$url->url = $data['urls'];
		  $this->urls[0] = $url;
		}
	  if( isset($data['catalogs'])) {
  		$catalog = new Catalog();
  		$catalog->type = 'PMID';
  		$catalog->identification = $data['catalogs'];
		  $this->catalogs[0] = $catalog;
		}
	}
}